package com.java110.mall.goods.cmd.allocationOrder;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.context.CmdContextUtils;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.allocationOrder.AllocationOrderDto;
import com.java110.dto.app.AppDto;
import com.java110.dto.product.ProductDto;
import com.java110.dto.product.ProductSpecValueDto;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.shop.ShopHouseDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.IAllocationOrderInnerServiceSMO;
import com.java110.intf.goods.IProductInnerServiceSMO;
import com.java110.intf.goods.IProductSpecValueInnerServiceSMO;
import com.java110.intf.shop.IShopHouseInnerServiceSMO;
import com.java110.intf.shop.IShopInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.account.AllocationOrderPo;
import com.java110.po.product.ProductPo;
import com.java110.po.product.ProductSpecValuePo;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Java110Cmd(serviceCode = "/allocationOrder/saveAllocationOrder")
public class SaveAllocationOrderCmd extends Cmd {

    @Autowired
    private IAllocationOrderInnerServiceSMO allocationOrderInnerServiceSMOImpl;

    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userV1InnerServiceSMOImpl;

    @Autowired
    private IShopHouseInnerServiceSMO shopHouseInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;

    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "srcShName", "请求报文中未包含srcShName");

    }

    @Override
    @Java110Transactional
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {

        String appId = cmdDataFlowContext.getReqHeaders().get("app-id");
        reqJson.put("appId", appId);

        String userId = CmdContextUtils.getUserId(cmdDataFlowContext);
        reqJson.put("userId",userId);

//        Assert.hasKeyAndValue(reqJson, "targetShName", "请求报文中未包含targetShName");
        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("userId"));
        userDto.setPage(1);
        userDto.setRow(1);
        List<UserDto> userDtos = userV1InnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "未查询到用户信息");

        AllocationOrderPo allocationOrderPo = BeanConvertUtil.covertBean(reqJson, AllocationOrderPo.class);
        allocationOrderPo.setStaffId(reqJson.getString("userId"));
        allocationOrderPo.setStaffName(userDtos.get(0).getName());
        allocationOrderPo.setProductCount(reqJson.getString("count"));
        allocationOrderPo.setActCount(reqJson.getString("count"));

        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(allocationOrderPo.getShopId());
        //查询商户
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        Assert.listOnlyOne(shopDtos, "查询商户错误！");
        ShopHouseDto shopHouseDto = new ShopHouseDto();
        shopHouseDto.setShId(allocationOrderPo.getTargetShId());
        //查询目标仓库
        List<ShopHouseDto> shopHouseDtos = shopHouseInnerServiceSMOImpl.queryShopHouses(shopHouseDto);
        Assert.listOnlyOne(shopHouseDtos, "查询目标仓库错误！");
        //获取目标仓库所属商铺ID
        String shopId = shopHouseDtos.get(0).getShopId();
        ShopDto shop = new ShopDto();
        shop.setShopId(shopId);
        //查询目标商户
        List<ShopDto> shops = shopInnerServiceSMOImpl.queryShops(shop);
        Assert.listOnlyOne(shops, "查询目标商户错误！");
        //商户名称
        allocationOrderPo.setShopName(shopDtos.get(0).getShopName());
        //目标商户id
        allocationOrderPo.setTargetShopId(shops.get(0).getShopId());
        //目标商户名称
        allocationOrderPo.setTargetShopName(shops.get(0).getShopName());
        //目标仓库名
        allocationOrderPo.setTargetShName(shopHouseDtos.get(0).getShName());
        //状态(1001 待审核 2002 待入库 3003 审核失败 4004 完成)
        allocationOrderPo.setState("1001");
        allocationOrderPo.setOrderId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_orderId));
        int flag = allocationOrderInnerServiceSMOImpl.saveAllocationOrder(allocationOrderPo);
        if (flag < 1) {
            throw new CmdException("保存失败");
        }
        ProductSpecValueDto productSpecValueDto = new ProductSpecValueDto();
        productSpecValueDto.setProductId(allocationOrderPo.getProductId());
        productSpecValueDto.setSpecId(allocationOrderPo.getSpecId());
        List<ProductSpecValueDto> productSpecValueDtos = productSpecValueInnerServiceSMOImpl.queryProductSpecValues(productSpecValueDto);
        Assert.listOnlyOne(productSpecValueDtos, "查询规格值错误");
        //获取库存
        String stock = productSpecValueDtos.get(0).getStock();
        //获取调拨数量
        String productCount = allocationOrderPo.getProductCount();
        //计算调拨后剩余库存
        double liveCount = Double.parseDouble(stock) - Double.parseDouble(productCount);
        ProductSpecValuePo productSpecValuePo = new ProductSpecValuePo();
        productSpecValuePo.setValueId(productSpecValueDtos.get(0).getValueId());
        productSpecValuePo.setStock(String.valueOf(liveCount));
        //更新库存
        productSpecValueInnerServiceSMOImpl.updateProductSpecValue(productSpecValuePo);
        //手机端 调拨取消审核功能
        hasFinish(reqJson,allocationOrderPo);
        cmdDataFlowContext.setResponseEntity(ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功"));
    }

    public void hasFinish(JSONObject reqJson, AllocationOrderPo allocationOrderPo) {
        if (!AppDto.MALL_STAFF_APP_ID.equals(reqJson.getString("appId"))) {
            return;
        }


        AllocationOrderPo tmpAllocationOrderPo = new AllocationOrderPo();
        tmpAllocationOrderPo.setOrderId(allocationOrderPo.getOrderId());
        tmpAllocationOrderPo.setState(AllocationOrderDto.STATE_FINISH);
        int flag = allocationOrderInnerServiceSMOImpl.updateAllocationOrder(tmpAllocationOrderPo);
        if (flag < 1) {
            throw new CmdException("审核失败");
        }

        ProductDto productDto = new ProductDto();
        productDto.setSpecId(allocationOrderPo.getSpecId()); //物品规格
        productDto.setShId(allocationOrderPo.getTargetShId()); //目标仓库
        productDto.setShopId(allocationOrderPo.getTargetShopId()); //目标商铺
        productDto.setProdName(allocationOrderPo.getProdName()); //商品名称
        //查询目标仓库下是否有该物品
        List<ProductDto> productDtos = productInnerServiceSMOImpl.queryProducts(productDto);
        if (productDtos != null && productDtos.size() == 1) { //目标仓库下有该商品
            //获取商品库存
            String stock = productDtos.get(0).getStock();
            //获取调拨库存
            String actCount = allocationOrderPo.getActCount();
            //计算调拨后总库存
            double allCount = Double.parseDouble(stock) + Double.parseDouble(actCount);
            ProductSpecValuePo productSpecValuePo = new ProductSpecValuePo();
            productSpecValuePo.setValueId(productDtos.get(0).getValueId());
            productSpecValuePo.setStock(String.valueOf(allCount));
            //更新商品库存
            productSpecValueInnerServiceSMOImpl.updateProductSpecValue(productSpecValuePo);
        } else if (productDtos != null && productDtos.size() > 1) {
            throw new IllegalArgumentException("查询目标仓库商品错误！");
        } else { //目标仓库下没有该商品
            //查询源仓库商品信息
            ProductDto productDt = new ProductDto();
            productDt.setProductId(allocationOrderPo.getProductId());
            List<ProductDto> productDts = productInnerServiceSMOImpl.queryProducts(productDt);
            Assert.listOnlyOne(productDts, "查询源仓库商品错误！");
            ProductPo product = new ProductPo();
            product.setProductId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_productId)); //商品id
            product.setStoreId(productDts.get(0).getStoreId()); //商户id
            product.setProdName(allocationOrderPo.getProdName()); //商品名称
            product.setProdDesc(allocationOrderPo.getProdName()); //商品简介
            product.setKeyword(allocationOrderPo.getProdName()); //关键字
            product.setBarCode(productDts.get(0).getBarCode()); //产品条码(一维码)
            product.setCategoryId(productDts.get(0).getCategoryId()); //分类id
            product.setUnitName(productDts.get(0).getUnitName()); //单位名称
            product.setSort(productDts.get(0).getSort()); //排序
            product.setState(productDts.get(0).getState()); //状态(1001：未上架，2002：上架)
            product.setPostage(productDts.get(0).getPostage()); //邮费
            product.setIsPostage(productDts.get(0).getIsPostage()); //是否包邮
            product.setShopId(allocationOrderPo.getTargetShopId()); //商铺id
            product.setShId(allocationOrderPo.getTargetShId()); //仓库id
            product.setShName(allocationOrderPo.getTargetShName()); //仓库名称
            product.setWarnStock(productDts.get(0).getWarnStock()); //库存警告数量
            product.setAreaCode(productDts.get(0).getAreaCode()); //城市编码
            //生成商品
            productInnerServiceSMOImpl.saveProduct(product);
            ProductSpecValueDto productSpecValueDto = new ProductSpecValueDto();
            productSpecValueDto.setValueId(productDts.get(0).getValueId());
            //查询源仓库商品规格值
            List<ProductSpecValueDto> productSpecValueDtos = productSpecValueInnerServiceSMOImpl.queryProductSpecValues(productSpecValueDto);
            Assert.listOnlyOne(productSpecValueDtos, "查询源仓库商品规格值表错误！");
            ProductSpecValuePo productSpecValuePo = new ProductSpecValuePo();
            productSpecValuePo.setValueId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_valueId)); //规格值id
            productSpecValuePo.setSpecId(allocationOrderPo.getSpecId()); //规格id
            productSpecValuePo.setProductId(product.getProductId()); //商品id
            productSpecValuePo.setStoreId(product.getStoreId()); //商户id
            productSpecValuePo.setStock(allocationOrderPo.getActCount()); //库存
            productSpecValuePo.setSales("0"); //销量
            productSpecValuePo.setPrice(productSpecValueDtos.get(0).getPrice()); //金额
            productSpecValuePo.setCostPrice(productSpecValueDtos.get(0).getCostPrice()); //成本价
            productSpecValuePo.setVipPrice(productSpecValueDtos.get(0).getVipPrice()); //会员价格
            productSpecValuePo.setOtPrice(productSpecValueDtos.get(0).getOtPrice()); //市场价格
            productSpecValuePo.setIsDefault(productSpecValueDtos.get(0).getIsDefault()); //是否为默认规格 T默认 F 不是
            productSpecValuePo.setShopId(allocationOrderPo.getTargetShopId()); //商铺id
            productSpecValuePo.setBarCode("-1"); //条形码
            productSpecValuePo.setWillExpire("0"); //七天内过期数量
            productSpecValuePo.setOwnerPrice(productSpecValueDtos.get(0).getOwnerPrice());
            productSpecValuePo.setDeduction(productSpecValueDtos.get(0).getDeduction());
            productSpecValuePo.setAttrition("0"); //耗损
            productSpecValueInnerServiceSMOImpl.saveProductSpecValue(productSpecValuePo);
        }
    }
}
